package com.edu.ujn.myh.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.ZipInputStream;

import org.jbpm.api.ExecutionService;
import org.jbpm.api.ProcessDefinition;
import org.jbpm.api.ProcessEngine;
import org.jbpm.api.ProcessInstance;
import org.jbpm.api.RepositoryService;
import org.jbpm.api.TaskService;
import org.jbpm.api.model.ActivityCoordinates;
import org.jbpm.api.task.Task;
import org.jbpm.pvm.internal.cfg.ConfigurationImpl;
import org.jbpm.pvm.internal.env.EnvironmentFactory;
import org.jbpm.pvm.internal.env.EnvironmentImpl;
import org.jbpm.pvm.internal.model.ExecutionImpl;
import org.jbpm.pvm.internal.session.DbSession;
import org.jbpm.pvm.internal.task.TaskImpl;

import com.edu.ujn.myh.domain.ActiveInfo;
import com.edu.ujn.myh.domain.ArticleInfo;
import com.edu.ujn.myh.domain.OpinionInfo;
import com.edu.ujn.myh.domain.TaskInfo;
import com.edu.ujn.myh.service.IApplyService;
import com.edu.ujn.myh.utils.StringToArray;
/**
 * 
 * @作者 马永华
 * @日期 2010-4-18下午05:28:43
 * @版本 1.0.0
 */
public class ArticleFlowAction extends BaseAction{
	
	private IApplyService applyService = null;
	private ProcessEngine processEngine = null;
	private RepositoryService repositoryService = null;// 存储服务
	private ProcessInstance processInstance = null; // 流程实例
	private ExecutionService executionService = null; // 执行服务
	private TaskService taskService = null;
	private File file = null;
	private String type = "";
	private String id ="";
	private String articleId[];
	private String professior = "";
	private String taskId = "";
	private String executionId = "";
	private String processId="";
	private String radioArray = "";
	private int artId ;//文章ID
	private String score;
	private String state;
	private String opinions ="";
//	初始化流程
	public String init(){
		ZipInputStream ziStream;
		repositoryService = processEngine.getRepositoryService();
		try {
			if(file==null){
//			如果上传文件为空则返回error
				return SUCCESS;
			}
			ziStream = new ZipInputStream(new FileInputStream(file));
			repositoryService.createDeployment().addResourcesFromZipInputStream(ziStream).deploy();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
//			启动流程失败
			return ERROR;
		}
		return SUCCESS;
	}
	public String getPDList(){
//		获得流程定义列表
		List pdList = null;
		repositoryService = processEngine.getRepositoryService();
		pdList =  repositoryService.createProcessDefinitionQuery().list();
		getRequest().setAttribute("pdList",pdList);
//		获得流程实例列表
		List piList = null;
		executionService = processEngine.getExecutionService();
		piList = executionService.createProcessInstanceQuery().list();
		getRequest().setAttribute("piList",piList);
		return SUCCESS;
	}
//	对流程定义进行相关操作（开始or删除）
	public String pdOperation(){
		if("start".equals(type)&&!"".equals(id)){
			try{
				executionService = processEngine.getExecutionService();
				executionService.startProcessInstanceById(id);
			}catch(Exception e){
				e.printStackTrace();
				return SUCCESS;
			}
		}else if("delete".equals(type)&&!"".equals(id)){
			try{
				repositoryService = processEngine.getRepositoryService();
				repositoryService.deleteDeployment(id);
			}catch(Exception e){
				e.printStackTrace();
				return SUCCESS;
			}
		}else if("end".equals(type)&&!"".equals(id)){
			try{
				executionService = processEngine.getExecutionService();
				executionService.endProcessInstance(id,ExecutionImpl.STATE_ENDED);
			}catch(Exception e){
				e.printStackTrace();
				return SUCCESS;
			}
		}
		return SUCCESS;
	}
//	获得主持人任务列表
	public String getZhuChiTaskList(){
		String userName = (String)getRequest().getSession().getAttribute("userName");
		if(userName==null||"".equals(userName)){
			return "login";
		}
		String name = "zhuchi";
		List taskList = getTaskList(name);
		
		getRequest().setAttribute("taskList",taskList);
		return SUCCESS;
	}
	
/*
 *  获得未分配的稿件信息
 */
	public String getArticleListFenPeiIsFalse(){
		String userName = (String)getRequest().getSession().getAttribute("userName");
		if(userName==null||"".equals(userName)){
			return "login";
		}
		List articleList = null;
//		获得文章列表
		articleList = applyService.getArticleList(0);
//		获得任务列表
		getRequest().setAttribute("articleList", articleList);
		getRequest().setAttribute("taskId",taskId);
		getRequest().setAttribute("processId",processId);
		return SUCCESS;
}
/*
 *分类完成，提交分类结果
 */
	public String postArticleAssort(){
		String userName = (String)getRequest().getSession().getAttribute("userName");
		if(userName==null||"".equals(userName)){
			return "login";
		}
//  	处理专家ID
		if("".equals(taskId)||"".equals(professior)||articleId==null||articleId.length==0){
			return ERROR;
		}
		 String[] profe = StringToArray.stringToArray(professior,"<>"); 
		 Map map1 = applyService.saveAP(articleId,profe,processId);
//		 获得专家对应的相关文章ID
//		 Map mapId = applyService.getProfessArticle(profe);
		 getRequest().getSession().setAttribute("profe",map1);
		 Map map = new HashMap();
		 map.put("select","会签");
		 String str = completeTask(taskId,map); 
		 if("error".equals(str)){
			return ERROR;
		 }
		 return SUCCESS;
	}
/*
 * 获得砖家任务列表
 * 
 */
	public String zjTaskList(){
		String userName = (String)getRequest().getSession().getAttribute("userName");
		int pId = (Integer)getRequest().getSession().getAttribute("pId");
		if(userName==null||"".equals(userName)){
			return "login";
		}
		String name = Integer.toString(pId);
		List list = getTaskList(name);
		getRequest().setAttribute("taskList",list);
		return SUCCESS;
	}
/*
* 得到专家的文章列表
* */
	public String getZJArticle(){
		String userName = (String)getRequest().getSession().getAttribute("userName");
		if(userName==null||"".equals(userName)){
			return "login";
		}
		List list = null;
		list = getVariables(taskId);
		List articleList = new ArrayList();
		for(int i=0;i<list.size();i++){
			String id = (String)list.get(i);
			ArticleInfo ai = new ArticleInfo();
			ai.setAId(Integer.parseInt(id));
			ArticleInfo articleInfo = applyService.getArticleInfo(ai);
			if(articleInfo!=null){
				articleList.add(articleInfo);
			}
		}
		getRequest().setAttribute("articleList",articleList);
		getRequest().setAttribute("taskId",taskId);
		getRequest().setAttribute("executionId",executionId);
		return SUCCESS;
	}

/*
 *专家提交会签任务 
 * 
 */
	public String completeZJTask(){     
		String userName = (String)getRequest().getSession().getAttribute("userName");
		int pId = (Integer)getRequest().getSession().getAttribute("pId");
		if(userName==null||"".equals(userName)){
			return "login";
		}
		if("".equals(taskId)){
			return ERROR;
		}
		String id = Integer.toString(pId);
//		专家完成任务
		Map map = new HashMap();
		map.put("userId", id);
		String str = completeHuiGao(executionId,map);
		if("error".equals(str)){
			return "error";
		}
		return SUCCESS;
	}
//	主持人统计
	public String  zhuChiStatistics(){
		String userName = (String)getRequest().getSession().getAttribute("userName");
		if(userName==null||"".equals(userName)){
			return "login";
		}
		ArticleInfo articleInfo = new ArticleInfo();
		articleInfo.setProcessId(processId);
		List articleList = applyService.getArticleInfo(articleInfo,1);
		getRequest().setAttribute("articleList",articleList);
		getRequest().setAttribute("taskId",taskId);
		return SUCCESS;
	}
//	主持人提交统计结果
	public String zhuChiPostResult(){
		String userName = (String)getRequest().getSession().getAttribute("userName");
		if(userName==null||"".equals(userName)){
			return "login";
		}
		List list = new ArrayList();
		System.out.println(radioArray);
		if(!"".equals(radioArray)){
			String str[] = StringToArray.stringToArray(radioArray,"<>");
			for(int i=0;i<str.length;i++){
				String str1 = str[i];
				String str2[] = StringToArray.stringToArray(str1,";");
				ArticleInfo articleInfo = new ArticleInfo();
				articleInfo.setAId(Integer.parseInt(str2[0]));
				articleInfo.setSpState(Integer.parseInt(str2[1]));
				list.add(articleInfo);
			}
		}
		String res = applyService.upDateArticle(list);
		if("error".equals(res)){
			return ERROR;
		}
		String re = completeTask(taskId,null);
		if("error".equals(re)){
			return ERROR;
		}
		return SUCCESS;
	}
//	得到文章的详细信息
	public String getArticleDetails(){
		String userName = (String)getRequest().getSession().getAttribute("userName");
		if(userName==null||"".equals(userName)){
			return "login";
		}
		ArticleInfo articleInfo = new ArticleInfo();
		articleInfo.setAId(artId);
		ArticleInfo article = applyService.getArticleInfo(articleInfo);
//		处理专家的意见信息
		getRequest().setAttribute("articleInfo",article);
		return SUCCESS;
	}
	
	
//	提交文章分数
	public String postScore(){
		String userName = (String)getRequest().getSession().getAttribute("userName");
		int pid = (Integer)getRequest().getSession().getAttribute("pId");
		if(userName==null||"".equals(userName)){
			return "login";
		}
		if(Float.valueOf(score)==50){
			state = "success";
			return SUCCESS;
		}
		ArticleInfo articleInfo = new ArticleInfo();
		articleInfo.setAId(artId);
		articleInfo.setScore(Float.valueOf(score));
//		articleInfo.setOpinions(opinions);
//	把字符串分割转换为意见对象
		if("".equals(opinions)){
		if(Float.valueOf(score)==50){
				state = "error";
				return SUCCESS;
			}
		}
		OpinionInfo opinionInfo = new OpinionInfo();
		opinionInfo.setaId(artId);
		opinionInfo.setpId(pid);
		String array1[] = opinions.split("<O>");
		String r1 = array1[0];
		String array2[] = r1.split("<S>");
		opinionInfo.setScore1(array2[0]);
		opinionInfo.setOpinion1(array2[1]);
		String r2 = array1[1];
		String array3[] = r2.split("<S>");
		opinionInfo.setScore2(array3[0]);
		opinionInfo.setOpinion2(array3[1]);
		String r3 = array1[2];
		String array4[] = r3.split("<S>");
		opinionInfo.setScore3(array4[0]);
		opinionInfo.setOpinion3(array4[1]);
		String r4 = array1[3];
		String array5[] = r4.split("<S>");
		opinionInfo.setScore4(array5[0]);
		opinionInfo.setOpinion4(array5[1]);
		String r5 = array1[4];
		String array6[] = r5.split("<S>");
		opinionInfo.setScore5(array6[0]);
		opinionInfo.setOpinion5(array6[1]);
		articleInfo.setOpinionInfo(opinionInfo);
		String str = applyService.upDateArticle(articleInfo);
		if("error".equals(str)){
			state = "error";
			return SUCCESS;
		}
		state = "success";
		return SUCCESS;
	}
//	获得流程图的参数
	public String getPicParam(){
		executionService = processEngine.getExecutionService();
		List<ProcessInstance> processInstance = null;
		try{
			processInstance = executionService.createProcessInstanceQuery().processInstanceId(processId).list();
		}catch(Exception e){
			getRequest().setAttribute("activeInfo",null);
			return SUCCESS;
		}
		Set<String> set = processInstance.get(0).findActiveActivityNames();
		System.out.println(set.size());
		String name = (String)set.toArray()[0];
		repositoryService = processEngine.getRepositoryService();
		ActivityCoordinates param = repositoryService.getActivityCoordinates("shengao-1",name);
		ActiveInfo activeInfo = new ActiveInfo();
		activeInfo.setX(param.getX());
		activeInfo.setY(param.getY());
		activeInfo.setWidth(param.getWidth());
		activeInfo.setHeight(param.getWidth());
		getRequest().setAttribute("activeInfo",activeInfo);
		return SUCCESS;
	}
//	获得流程图片
	public void getPicStream(){
		repositoryService = processEngine.getRepositoryService();
		ProcessDefinition processDefinition = null;
		List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery().list();
		for(int i=0;i<list.size();i++){
			ProcessDefinition p = list.get(i);
			if(processDefinition==null){
				processDefinition = p;
			}else {
				if(processDefinition.getVersion()<p.getVersion()){
					processDefinition = p;
				}
			}
		}
		try{
//			processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId("shengao-1").uniqueResult();
			System.out.println(processDefinition.getId());
		}catch(Exception e){
			e.printStackTrace();
		}
		InputStream in = repositoryService.getResourceAsStream(processDefinition.getDeploymentId(), processDefinition.getImageResourceName());
		try {
		     if(in!=null)
	            {
	                byte[] bytes = new byte[1024*4];
	                int size = 0;
	                //输出流程图
	                while ((size = in.read(bytes,0,1024*4))!= -1) {
	                    getResponse().getOutputStream().write(bytes,0,size);
	                }
	            }
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
/*
 * 获得任务列表
 */
	public List<TaskInfo> getTaskList(String username) {
		taskService = processEngine.getTaskService();
		List<Task> list = taskService.createTaskQuery().assignee(username).list();
		Iterator<Task> iter = list.iterator();
		List<TaskInfo> returnList = new ArrayList<TaskInfo>();
		while (iter.hasNext()) {
			TaskInfo taskInfo = new TaskInfo();
			Task task = iter.next();
			List a = (List)taskService.getVariable(task.getId(),"articleList");
			taskInfo.setTaskId(task.getId());
			taskInfo.setTaskName(task.getName());
			taskInfo.setExecutionId(task.getExecutionId());
			taskInfo.setUserName(username);
			String executionid = task.getExecutionId();
			// 如果该task没有executionid，则从父task获得executionid
			if (executionid == null || executionid.equals("")) {
				EnvironmentFactory environmentFactory = null;
				EnvironmentImpl environmentImpl = null;
				try {
					environmentFactory = (EnvironmentFactory) new ConfigurationImpl()
							.buildProcessEngine();
					environmentImpl = environmentFactory.openEnvironment();
					DbSession dbsession = environmentImpl.get(DbSession.class);
					TaskImpl taskimpl = (TaskImpl) dbsession.get(
							TaskImpl.class, Long.parseLong(task.getId()));
					executionid = taskimpl.getSuperTask().getExecutionId();
				} finally {
					if (environmentImpl != null)
						environmentImpl.close();
				}
			}
			taskInfo.setExecutionId(executionid);
			returnList.add(taskInfo);
		}
		return returnList;
	}
//	完成任务
	public String completeTask(String id,Map map){
		try{
			taskService = processEngine.getTaskService();
			if(map!=null){
			taskService.setVariables(id, map);
			}
			taskService.completeTask(id);
		}catch(Exception e){
			e.printStackTrace();
			return "error";
		}
		return "success";
	}

//	得到任务中variables
	public List getVariables(String taskId){
		taskService = processEngine.getTaskService();
		List list = (List)taskService.getVariable(taskId, "articleList");
		return list;
	}
//	完成会稿
	public String completeHuiGao(String taskId,Map map){
		try{
			executionService = processEngine.getExecutionService();
			executionService.signalExecutionById(taskId, map);
		}catch(Exception e){
			e.printStackTrace();
			return "error";
		}
		return SUCCESS;
	}

	public ProcessEngine getProcessEngine() {
		return processEngine;
	}
	public void setProcessEngine(ProcessEngine processEngine) {
		this.processEngine = processEngine;
	}
	public RepositoryService getRepositoryService() {
		return repositoryService;
	}
	public void setRepositoryService(RepositoryService repositoryService) {
		this.repositoryService = repositoryService;
	}
	public ProcessInstance getProcessInstance() {
		return processInstance;
	}
	public void setProcessInstance(ProcessInstance processInstance) {
		this.processInstance = processInstance;
	}
	public ExecutionService getExecutionService() {
		return executionService;
	}
	public void setExecutionService(ExecutionService executionService) {
		this.executionService = executionService;
	}
	public TaskService getTaskService() {
		return taskService;
	}
	public void setTaskService(TaskService taskService) {
		this.taskService = taskService;
	}
	public File getFile() {
		return file;
	}
	public void setFile(File file) {
		this.file = file;
	}
	public void setApplyService(IApplyService applyService) {
		this.applyService = applyService;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public void setProfessior(String professior) {
		this.professior = professior;
	}
	public void setArticleId(String[] articleId) {
		this.articleId = articleId;
	}
	public void setTaskId(String taskId) {
		this.taskId = taskId;
	}
	public void setExecutionId(String executionId) {
		this.executionId = executionId;
	}
	public void setProcessId(String processId) {
		this.processId = processId;
	}
	public void setRadioArray(String radioArray) {
		this.radioArray = radioArray;
	}
	public void setArtId(int artId) {
		this.artId = artId;
	}
	public void setScore(String score) {
		this.score = score;
	}
	public String getState() {
		return state;
	}
	public void setState(String state) {
		this.state = state;
	}
	public void setOpinions(String opinions) {
		this.opinions = opinions;
	}
}
